package com.ziven.common.widget.title;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.DimenRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.ziven.easygo.util.ViewHelper;

/**
 * @author Ziven
 */
public class TitleView extends Toolbar {

    private TextView titleView;
    private TextView subtitleView;

    public TitleView(@NonNull Context context) {
        super(context);
    }

    public TitleView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TitleView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if(titleView == null) {
            titleView = obtainTitleView(title);
        }
    }

    @Override
    public void setSubtitle(CharSequence subtitle) {
        super.setSubtitle(subtitle);
        if(subtitleView == null) {
            subtitleView = obtainTitleView(subtitle);
        }
    }

    @Nullable
    private TextView obtainTitleView(CharSequence title) {
        if(TextUtils.isEmpty(title)) {
            return null;
        }
        View view;
        int count = getChildCount();
        for(int i=0; i<count; i++) {
            if((view = getChildAt(i)) instanceof TextView
                    && TextUtils.equals(title, ((TextView) view).getText())) {
                return (TextView) view;
            }
        }
        return null;
    }

    /**
     * After setSubtitle
     * @return Title: TextView
     */
    @Nullable
    public TextView getTitleView() {
        return titleView;
    }

    /**
     * After setSubtitle
     * @return Subtitle: TextView
     */
    @Nullable
    public TextView getSubtitleView() {
        return subtitleView;
    }

    public void setTitleSizeId(@DimenRes int sizeId) {
        ViewHelper.create(getTitleView()).setTextSizeId(sizeId);
    }

    public void setSubtitleSizeId(@DimenRes int sizeId) {
        ViewHelper.create(getSubtitleView()).setTextSizeId(sizeId);
    }

    public void setTitleSize(float size) {
        ViewHelper.create(getTitleView()).setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
    }

    public void setSubtitleSize(float size) {
        ViewHelper.create(getSubtitleView()).setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
    }
}
